﻿@page "/HtFilmList"
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using HtERP.Data
@using ClosedXML.Excel
@inject IJSRuntime JS
@attribute [Authorize]

<PageTitle>HtFilmList</PageTitle>

<div>
    <strong><font size="5" style="color:#016f5e">菲林输出</font></strong>
    <em>（共: <strong>@numResults() </strong>条，数量: <strong>@TotalQuantity() </strong>，价格: <strong>@Totalprice()</strong>元。）</em>
    <button class="btn btn-primary" @onclick="DownloadExcel">下载Excel</button>
    <button class="btn btn-primary" @onclick="查询今天">今天</button>
    <button class="btn btn-primary" @onclick="查询昨天">昨天</button>
    <button class="btn btn-primary" @onclick="查询前天">前天</button>
    编号
    <input @bind="Text1" id="t1" type="number" style="width:110px; background-color:antiquewhite" />
    <button class="btn btn-primary" @onclick="按编号查询">按编号查询</button>

</div>

<div>
    <input @bind="date1" id="tt" type="date" style="width:120px" />
    <input @bind="date2" id="tt" type="date" style="width:120px" />
    <input type="search" autofocus @bind="nameFilter" placeholder="客户..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter1" placeholder="工作名..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter3" placeholder="要求说明..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter4" placeholder="送货地点..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter5" placeholder="制作员..." style="width:120px" />
    <button class="btn btn-primary" @onclick="查询">查询</button>
    <button class="btn btn-primary" @onclick="清空搜索项">清空搜索项</button>
</div>

<div>
@if (items == null)
{
    <p><em>Loading...</em></p>
}
else
{
        <table class="table tablemini" id="editableTable">
        <thead>
            <tr class="ttr">
                <th><button class="btn trbtn" @onclick="编号排序">编号<img src="@bhimg" width="18" alt="↓" /></button></th>
                <th><button class="btn trbtn" @onclick="日期排序">日期<img src="@rqimg" width="18" alt="↓" /></button></th>
                <th><button class="btn trbtn" @onclick="客户排序">客户<img src="@khimg" width="18" alt="↓" /></button></th>
                <th>文件或工作名</th>
                <th>长</th>
                <th>宽</th>
                <th>张数</th>
                <th>要求说明</th>
                <th>送货地点</th>
                <th style="background-color:rgba(255,225,215,0.5)">急</th>
                <th>线数</th>
                <th>网点类型</th>
                <th>方向</th>
                <th>完成</th>
                <th>包装</th>
                <th>备注</th>
                <th>菲林费</th>
                <th>设计费</th>
                <th>其他费用</th>
                <th>已优惠</th>
                <th>应收金额</th>
                <th>结清</th>
                <th>输出设备</th>
                <th>制作员</th>
                <th>x</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in items)
            {
                <tr>
                    <td style ="width:70px">@forecast.编号</td>
                    <td><input @bind="forecast.输出日期" id="日期" type="date" style="width:98px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td>
                        <input @bind="forecast.客户" type="text" style="min-width:108px" @bind:after="@(() => 更新数据(forecast))" @onclick="khLoadList" list="options" />
                        <datalist id="options">
                            <option value="现金"></option>
                            <option value="临时"></option>
                            @if (kh != null) foreach (var fore in kh)
                                {
                                    <option value="@fore.客户ID"></option>
                                }
                            <!-- 更多选项 -->
                        </datalist>
                    </td>
                    <td><input @bind="forecast.文件或工作名" type="text" style="min-width:228px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td><input @bind="forecast.长" type="text" style="width:42px; text-align: right; background-color:rgba(235,255,215,0.3)" @bind:after="@(() => 菲林价格计算(forecast))" /></td>
                    <td><input @bind="forecast.宽" type="text" style="width:42px; text-align: right; background-color:rgba(235,255,215,0.3)" @bind:after="@(() => 菲林价格计算(forecast))" /></td>
                    <td><input @bind="forecast.总色数" type="text" style="width:42px; text-align: center" @bind:after="@(() => 菲林价格计算(forecast))" /></td>
                    <td><input @bind="forecast.输出要求" type="text" style="min-width:168px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td><input @bind="forecast.送货地点" type="text" style="min-width:88px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td><input @bind="forecast.急" type="checkbox" style="width:28px; background-color:rgba(255,225,215,0.5)" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td><input @bind="forecast.加网线数" type="text" style="width:38px" @bind:after="@(() => 更新数据(forecast))" /></td>
                        <td>
                            <input @bind="forecast.网点类型" type="text" @onclick="wdLoadList" list="wdoptions" style=" min-width:60px" @bind:after="@(() => 更新数据(forecast))" />
                            <datalist id="wdoptions">
                                @if (wdlist != null) foreach (var forzz in wdlist)
                                    {
                                        <option value="@forzz.网点类型"></option>
                                    }
                            </datalist>
                        </td>
                    <td>
                        <input @bind="@(forecast.输出方向)" list="fxoptions" type="text" style="width:38px" @bind:after="@(() => 更新数据(forecast))" />
                        <datalist id="fxoptions">
                            <option value="横"></option>
                            <option value="竖"></option>
                        </datalist>
                    </td>
                    <td><input @bind="forecast.已完成" type="checkbox" style="width:28px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td><input @bind="forecast.包装完成" type="checkbox" style="width:28px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td><input @bind="forecast.备注" type="text" style="width:50px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td>
                            <input type="number" style="text-align: right;width:58px; background-color:rgba(255,255,228,0.5)"
                                   value="@(forecast.版费?.ToString("F2") ?? "NULL")"
                                   @onchange="@(e => forecast.版费 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                                   @onblur="@(() => 价格合计(forecast))"/>
                    </td>
                    <td>
                            <input type="number" style="text-align: right;width:58px; background-color:rgba(225,255,238,0.5)"
                                   value="@(forecast.设计制作费?.ToString("F2") ?? "NULL")"
                                   @onchange="@(e => forecast.设计制作费 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                                   @onblur="@(() => 价格合计(forecast))"/>
                    </td>
                    <td>
                            <input type="number" style="text-align: right;width:58px; background-color:rgba(255,235,228,0.5)"
                                   value="@(forecast.其他费用?.ToString("F2") ?? "NULL")"
                                   @onchange="@(e => forecast.其他费用 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                                   @onblur="@(() => 价格合计(forecast))"/>
                    </td>
                    <td><input @bind="forecast.已优惠" type="checkbox" style="width:28px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td>
                            <input type="number" style="text-align: right; width:68px; background-color:rgba(255,255,208,0.5)"
                                   value="@(forecast.应收?.ToString("F2") ?? "NULL")"
                                   @onchange="@(e => forecast.应收 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                                   @onblur="@(() => 更新数据(forecast))" />
                    </td>
                        <td><input @bind="forecast.结清" type="checkbox" style="width:28px" disabled /></td>
                        <td><input @bind="forecast.输出设备" type="text" style="width:68px" @bind:after="@(() => 更新数据(forecast))" /></td>
                    <td>
                        <input @bind="forecast.制作员1" type="text" style="width:66px" @bind:after="@(() => 更新数据(forecast))" @onclick="ygLoadList" list="ygoptions" />
                        <datalist id="ygoptions">
                            @if (yglist != null) foreach (var foryg in yglist)
                                {
                                    <option value="@foryg.姓名"></option>
                                }
                        </datalist>
                    </td>
                        <td> <button class="btn trbtn" @onclick="@(() => ShowDeleteEvent(forecast))" style="color:red">删</button></td>
                </tr>
            }
        </tbody>
    </table>
}

<p> <button class="btn btn-primary" @onclick="新插一行">新建</button>   共: <strong>@numResults()</strong>条</p>
</div>

@if (ShowDelete)
{
    <div class="custom-dialog" @onclick:stopPropagation>
        <div class="dialog-content">
            <h3> 是否确定要删除：</h3>
            <h4> @aa</h4>
            <p><button class="dialog-button" @onclick="Deleteit">确定删除</button> <button class="dialog-button" @onclick="HideDeleteEvent">取消</button></p>
        </div>
    </div>
}


@code {

    [CascadingParameter]
    private Task<AuthenticationState>? authenticationState { get; set; }

    AuthState? AuthState;

    int? Text1 = null;
    DateTime date1 = DateTime.Now.AddDays(-1);
    DateTime date2 = DateTime.Now;

    string nameFilter = string.Empty;
    string nameFilter1 = string.Empty;
    string nameFilter2 = string.Empty;
    string nameFilter3 = string.Empty;
    string nameFilter4 = string.Empty;
    string nameFilter5 = string.Empty;

    private 菲林制作输出表[]? forecasts;
    private IQueryable<菲林制作输出表>? items;
    protected override async Task OnInitializedAsync()
    {
        AuthState = authenticationState?.Result as AuthState;
        forecasts = HongtengDbCon.Db.Queryable<菲林制作输出表>().Where(it => it.输出日期.Value.Date == date2.Date).Where(it => it.IsDelete == false).ToArray();
        items = forecasts.OrderBy(p => p.编号).AsQueryable();
        await InvokeAsync(StateHasChanged);
    }

    public int numResults()
    {
        int Count = items.Count();
        return Count;
    }
    public float? TotalQuantity()  //数量合计
    {
        float? total = items.Sum(item => item.总色数);
        return total;
    }
    public decimal? Totalprice()  //价格合计
    {
        decimal? total = items.Sum(item => item.应收);
        return total;
    }

    private 客户[]? kh;
    private void khLoadList()
    {
        kh = HongtengDbCon.Db.Queryable<客户>().Where(it => it.IsDelete == false).ToArray();
    }

    public 员工[] yglist;
    private void ygLoadList()
    {
        yglist = HongtengDbCon.Db.Queryable<员工>().Where(it => it.是否已离职 != true).ToArray();
    }

    public CTP网点类型[] wdlist;
    private void wdLoadList()
    {
        wdlist = HongtengDbCon.Db.Queryable<CTP网点类型>().ToArray();
    }

    private void 查询今天()
    {
        forecasts = HongtengDbCon.Db.Queryable<菲林制作输出表>().Where(it => it.输出日期.Value.Date == DateTime.Now.Date).Where(it => it.IsDelete == false).ToArray();
        items = forecasts.AsQueryable().Where(it => it.IsDelete == false);
    }
    private void 查询昨天()
    {
        forecasts = HongtengDbCon.Db.Queryable<菲林制作输出表>().Where(it => it.输出日期.Value.Date == DateTime.Now.AddDays(-1).Date).Where(it => it.IsDelete == false).ToArray();
        items = forecasts.AsQueryable().Where(it => it.IsDelete == false);
    }
    private void 查询前天()
    {
        forecasts = HongtengDbCon.Db.Queryable<菲林制作输出表>().Where(it => it.输出日期.Value.Date == DateTime.Now.AddDays(-2).Date).Where(it => it.IsDelete == false).ToArray();
        items = forecasts.AsQueryable().Where(it => it.IsDelete == false);
    }
    private void 按编号查询()
    {
        if (Text1 > 0)
        {
            forecasts = HongtengDbCon.Db.Queryable<菲林制作输出表>().Where(it => it.编号 == Text1).ToArray();
            items = forecasts.AsQueryable();
        }

    }

    private void 查询()
    {
        DateTime d1 = date1;
        DateTime d2 = date2;

        if (date2 < date1)
        {
            d1 = date2;
            d2 = date1;
        }


        forecasts = HongtengDbCon.Db.Queryable<菲林制作输出表>().Where(it => it.IsDelete == false)
             .WhereIF(true, it => it.输出日期.Value.Date >= d1.Date && it.输出日期.Value.Date <= d2.Date)
             .WhereIF(!string.IsNullOrEmpty(nameFilter), it => it.客户.Contains(nameFilter))
             .WhereIF(!string.IsNullOrEmpty(nameFilter1), it => it.文件或工作名.Contains(nameFilter1))
             .WhereIF(!string.IsNullOrEmpty(nameFilter3), it => it.输出要求.Contains(nameFilter3))
             .WhereIF(!string.IsNullOrEmpty(nameFilter4), it => it.送货地点.Contains(nameFilter4))
             .WhereIF(!string.IsNullOrEmpty(nameFilter5), it => it.制作员1.Contains(nameFilter5)).ToArray();

        items = forecasts.AsQueryable();

    }


    private void 清空搜索项()
    {

        nameFilter = string.Empty;
        nameFilter1 = string.Empty;
        nameFilter2 = string.Empty;
        nameFilter3 = string.Empty;
        nameFilter4 = string.Empty;
        nameFilter5 = string.Empty;

    }

    private void 新插一行()
    {
        var ddd = HongtengDbCon.Db.Insertable(new 菲林制作输出表() { 输出日期 = DateTime.Now, 制作员1 = AuthState?.UserName, 总色数 = 0, 其他费用 = 0, 设计制作费 = 0, 应收 = 0 }).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntity();
        var dda = forecasts.ToList();
        dda.Add(ddd);
        forecasts = dda.ToArray();
        items = forecasts.AsQueryable().Where(it => it.IsDelete == false);
    }

    private void 更新数据(菲林制作输出表 p)
    {
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(p).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
    }

    /// <summary>
    /// 排序
    /// </summary>
    int bh = 0;
    string bhimg = "/image/arrowUp.svg";
    private void 编号排序()
    {
        if (bh == 0)
        {
            items = items.OrderBy(p => p.编号).AsQueryable(); //顺序排序
            bh = 1;
            bhimg = "/image/arrowUp.svg";
        }
        else
        {
            items = items.OrderByDescending(p => p.编号).AsQueryable(); //倒叙排序
            bh = 0;
            bhimg = "/image/arrowDown.svg";
        }
    }

    int rq = 0;
    string rqimg = "/image/arrowUp.svg";
    private void 日期排序()
    {
        if (rq == 0)
        {
            items = items.OrderBy(p => p.输出日期).AsQueryable(); //顺序排序
            rq = 1;
            rqimg = "/image/arrowUp.svg";
        }
        else
        {
            items = items.OrderByDescending(p => p.输出日期).AsQueryable(); //倒叙排序
            rq = 0;
            rqimg = "/image/arrowDown.svg";
        }
    }

    int kk = 0;
    string khimg = "/image/arrowUp.svg";
    private void 客户排序()
    {
        if (kk == 0)
        {
            items = items.OrderBy(p => p.客户).AsQueryable(); //顺序排序
            kk = 1;
            khimg = "/image/arrowUp.svg";
        }
        else
        {
            items = items.OrderByDescending(p => p.客户).AsQueryable(); //倒叙排序
            kk = 0;
            khimg = "/image/arrowDown.svg";
        }
    }

    private void 完成排序()
    {
        items = items.OrderByDescending(p => p.已完成).AsQueryable(); //排序
    }

    private void 菲林价格计算(菲林制作输出表 p)
    {
        float c = 0;//长
        float k = 0;//宽
        float s = 0;//张数
        decimal qb = 0;//起步价
        decimal flf = 0;//菲林费
        decimal sjf = 0;//设计制作费
        decimal qtf = 0;//其他费用
        decimal dj = 0;//菲林每平米价格
        if (p.长>0)
        {
            c = p.长 ?? 0; ;
        }
        if (p.宽 > 0)
        {
            k = p.宽 ?? 0; ;
        }
        if (p.总色数 > 0)
        {
            s = p.总色数 ?? 0;
        }
        if (p.设计制作费 > 0)
        {
            sjf = p.设计制作费 ?? 0;
        }
        if (p.其他费用 > 0)
        {
            qtf = p.其他费用 ?? 0;
        }
        qb = HongtengDbCon.Db.Queryable<公用设置>().First(it => it.ID == 1).菲林起步价 ?? 0;
        dj = HongtengDbCon.Db.Queryable<公用设置>().First(it => it.ID == 1).菲林每平米价格 ?? 0;
        double aa = Math.Ceiling(c * k  * 0.000001 * ((float)dj));
        if (((decimal)aa) < qb)
        {
            flf = qb * ((decimal)s);
        }
        else
        {
            flf = ((decimal)Math.Ceiling(c * k * 0.000001* s * ((float)dj)));
        }
        p.版费 = flf;
        p.应收 = flf + sjf + qtf;

        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(p).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
    }

    private void 价格合计(菲林制作输出表 p)
    {
        decimal flf = 0;//菲林费
        decimal sjf = 0;//设计制作费
        decimal qtf = 0;//其他费用

        if (p.版费 > 0)
        {
            flf = p.版费 ?? 0;
        }
        if (p.设计制作费 > 0)
        {
            sjf = p.设计制作费 ?? 0;
        }
        if (p.其他费用 > 0)
        {
            qtf = p.其他费用 ?? 0;
        }
      
        p.应收 = flf + sjf + qtf;

        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(p).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
    }
    
    //弹出窗口-软删除一条
    string? aa;
    public 菲林制作输出表? pp;
    public bool ShowDelete { get; set; }
    private void HideDeleteEvent()
    {
        ShowDelete = false;
    }
    private void ShowDeleteEvent(菲林制作输出表 p)
    {
        pp = p;
        aa = pp.编号 + "，" + pp.客户 + "【" + pp.文件或工作名 + "】";
        ShowDelete = true;
    }
    private void Deleteit()
    {
        pp.IsDelete = true;
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(pp).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
        items = forecasts.AsQueryable().Where(it => it.IsDelete == false);

        ShowDelete = false;
    }

    public async Task DownloadExcel()
    {
        using (XLWorkbook workbook = new XLWorkbook())
        {
            IXLWorksheet worksheet = workbook.AddWorksheet("Mysheet");

           
            worksheet.Cell(1, 1).Value = "编号";
            worksheet.Cell(1, 2).Value = "日期";
            worksheet.Cell(1, 3).Value = "客户";
            worksheet.Cell(1, 4).Value = "工作名";
            worksheet.Cell(1, 5).Value = "长";
            worksheet.Cell(1, 6).Value = "宽";
            worksheet.Cell(1, 7).Value = "张数";
            worksheet.Cell(1, 8).Value = "价格";
            worksheet.Cell(1, 9).Value = "要求";
            worksheet.Cell(1, 10).Value = "送货地址";
            worksheet.Cell(1, 11).Value = "制作员";
            worksheet.Cell(1, 12).Value = "备注";

            worksheet.Row(1).Style.Font.Bold = true;


            int row = 2;
            foreach (var forzz in items)
            {
                
                worksheet.Cell(row, 1).Value = forzz.编号.ToString();
                worksheet.Cell(row, 2).Value = forzz.输出日期;
                worksheet.Cell(row, 3).Value = forzz.客户;
                worksheet.Cell(row, 4).Value = forzz.文件或工作名;
                worksheet.Cell(row, 5).Value = forzz.长;
                worksheet.Cell(row, 6).Value = forzz.宽;
                worksheet.Cell(row, 7).Value = forzz.总色数;
                worksheet.Cell(row, 8).Value = forzz.应收;
                worksheet.Cell(row, 9).Value = forzz.输出要求;
                worksheet.Cell(row, 10).Value = forzz.送货地点;
                worksheet.Cell(row, 11).Value = forzz.制作员1;
                worksheet.Cell(row, 12).Value = forzz.备注;
                row++;
            }


            // 创建内存流用于保存工作簿
            using (var memoryStream = new MemoryStream())
            {
                // 将工作簿保存到内存流中
                workbook.SaveAs(memoryStream);

                // 重置内存流的位置，以确保从头开始读取
                memoryStream.Position = 0;

                // 这里可以将内存流进行进一步处理，例如发送为电子邮件附件或者作为API响应返回等
                var fileName = "菲林输出" + DateTime.Now.ToString()+".xlsx";

                using var streamRef = new DotNetStreamReference(stream: memoryStream);

                await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
            }
        }

    }



}
